package com.zhongen.oa.controller;

import com.zhongen.common.security.annotation.Inner;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * 获取小程序token
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/applet")
@Tag(description = "applet", name = "微信小程序")
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class AppletController {

	private static final Logger log = LoggerFactory.getLogger(AppletController.class);

	@Inner(false)
	@GetMapping("/wxpush")
	@Operation(summary = "微信推送")
	public String wxpush(HttpServletRequest request, String signature, String timestamp, String nonce, String echostr) {
		log.info("微信推送请求参数：signature={};timestamp={};nonce={};echostr={}", signature, timestamp, nonce, echostr);
		if (request.getMethod().equalsIgnoreCase("get")) {// 用来校验，一般会验证前端配置的token等，这里简化了代码。
			return "我请求到了";
		}
		else if (request.getMethod().equalsIgnoreCase("POST")) {// 接收用户的相关行为事件结果
			try {
				BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
				StringBuilder requestContent = new StringBuilder();
				String line;
				while ((line = reader.readLine()) != null) {
					requestContent.append(line);
				}
				reader.close();
				// 接收：{"ToUserName":"gh_ea84a199bf81","FromUserName":"oG0NJ5Oi_3Dd1HlZJ14xfnA0sJ6s","CreateTime":1686131943,"MsgType":"event","Event":"subscribe_msg_popup_event","List":{"PopupScene":"0","SubscribeStatusString":"accept","TemplateId":"4ondVRxk4L20ihrJ3iI15BDK72XatGPxE0MeCVwHasQ"}}
				return "";
			}
			catch (IOException e) {
				// 处理异常情况
				e.printStackTrace();
				return e.toString();
			}
		}
		else {
			return null;
		}
	}

}
